<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Company extends CI_Controller {

    private $_data;

    function __construct() {
        parent::__construct();
        $this->load->model(array('companymodel', 'ratemodel', 'company_comment_model', 'eventmodel', 'bid_model', 'usermodel'));

        if ($this->router->method != 'index' AND $this->router->method != 'view') {
            if (!isset($_SESSION['userLoggedIn'])) {
                redirect();
            }
        }
    }

    /**
     * Action index
     * Hiển thị danh sách tất cả các Công ty
     */
    public function index($page = 0, $isAjax = FALSE, $categoryId = NULL, $filter = NULL) {
        $this->load->helper('frontend');
        $this->load->helper('user_helper');
        
        $data['bids'] = $this->bid_model->getAllBidByType(3);
        
        if ($categoryId && $categoryId!= 'null') {
            $data['companys'] = $this->companymodel->getCompanysByCategoryId(8, $page * 8, $categoryId);
        } else {
            $data['companys'] = $this->companymodel->getCompanys(8, $page * 8);
        }
        if($filter != 'null') {
            $data['filter'] = $filter;
            if($filter == 'rate') {
                $data['companys'] = $this->companymodel->getHighestRateCompanys(8, $page * 8);
            } else if($filter == 'recruitment') {
                $data['companys'] = $this->companymodel->getCompanysWithRecruitment(8, $page * 8);
            }
        }
        if(isset($data['companys']) && $data['companys'] != "") {
            for($i = 0; $i < count($data['companys']); $i++) {
                //Get event mới nhất của company (nếu có)
                $data['companys'][$i]['event'] = $this->eventmodel->getNewestEventByCidAndType($data['companys'][$i]['company_id'], 1);
                //Count comment của company
                $count_comment = $this->company_comment_model->getCountCommentByCompanyId($data['companys'][$i]['company_id']);
                if($count_comment['count'] < 10) {
                    $count_comment['count'] = '0' . $count_comment['count'];
                }
                $data['companys'][$i]['count_comment'] = $count_comment['count'];
            }
        }
        if ($page) {
            $data['extra'] = true;
        }
        if(isset($_SESSION['userLoggedIn'])) {
             $data['user'] = $this->usermodel->getUserByid((int) $_SESSION['userLoggedIn']['id']);
        }
        if ($isAjax) {
            $this->load->view('company/index', $data);
        } else {
            $this->_data['content'] = $this->load->view('company/index', $data, true);
            $this->load->view('layout/frontend/index', $this->_data);
        }
    }

    /**
     * Action view
     * Xem chi tiết thông tin của một công ty
     */
    public function view($slug, $isAjax = FALSE) {
        $this->load->helper('frontend');
        $this->load->helper('user_helper');
        $this->companymodel->updateViewed($slug);
        $data['not_login'] = "";
        $data['rated'] = "";

        // Kiểm tra xem người dùng đã đăng nhập hay chưa
        if (!isset($_SESSION['userLoggedIn'])) {
            $data['not_login'] = 1;
        }

        if ($isAjax) {
            $data['company'] = $this->companymodel->getCompanyBySlug($slug);
            if (isset($data['company']['company_id']) && $data['company']['company_id'] != "") {
                $rated_id = $data['company']['company_id'];
                // Kiểm tra xem người dùng đã rate cho công ty này chưa
                if (isset($_SESSION['userLoggedIn'])) {
                    $data['rate'] = $this->ratemodel->getRateByUserIdAndRatedIdAndType((int) $_SESSION['userLoggedIn']['id'], $rated_id, 1);
                    if (isset($data['rate']['id']) && $data['rate']['id'] != "") {
                        $data['rated'] = 1;
                    }
                }
                // Lấy danh sách các comment
                $data['comment'] = $this->company_comment_model->getCommentByCompanyId($data['company']['company_id'], 0, 10);
                if (count($data['comment']) == 0) {
                    $data['check_comment'] = 0;
                }
            }
            $this->load->view('company/view', $data);
        } else {
            $data = array('slug' => $slug);
            $this->_data['content'] = $this->load->view('company/search', $data, true);
            $this->load->view('layout/frontend/index', $this->_data);
        }
    }

    /**
     * Ajax Action
     * Hiển thị danh sách tất cả các Công ty
     */
    public function uploadBanner() {
        if (isset($_FILES['banner']) && !empty($_FILES['banner']['name'])) {
            $this->load->library('upload');
            $this->load->library('image_lib');

            $this->upload->initialize(array(
                'upload_path' => 'upload/company/banner/',
                'allowed_types' => 'gif|jpg|png|jpeg',
            ));
            $_POST['banner'] = $this->_upload('banner', array(
                'resize' => TRUE,
                'width' => 949,
                'height' => 245,
                'source_image' => 'upload/company/banner/',
            ));

//		    if (isset($company_id) && $data['company']['logo']) {
//		        unlink('upload/company/logo/' . $data['company']['logo']);
//		    }

            sleep(1);
            echo '<script type="text/javascript">window.top.window.finishUpload("' . $_POST['banner'] . '");</script>';
        }
    }

    public function add() {
        $this->load->helper('frontend');
        $this->load->library(array('form_validation'));

        $data['company'] = $this->companymodel->getCompanyByUserId((int) $_SESSION['userLoggedIn']['id']);
        // Công ty là chưa được tạo, khởi tạo các giá trị cho edit là empty
        if (!$data['company']) {
            $data['company'] = array(
                'company_id' => '',
                'logo' => '',
                'avatar' => '',
                'name' => '',
                'abbreviation' => '',
                'english_name' => '',
                'address' => '',
                'tax_code' => '',
                'tel' => '',
                'website' => '',
                'email' => '',
                'representative' => '',
                'cellphone' => '',
                'charter_capital' => '',
                'business_types' => '',
                'businesses' => '',
                'business_license_issued_on' => '',
                'other_businesses' => '',
                'posting_area' => '',
                'company_background' => '',
                'intro_images' => ';;;;',
                'intro_video' => '',
                'album' => ';;;;;;;',
                'date' => '',
                'quantity' => '',
                'property' => '',
                'work_place' => '',
                'career' => '',
                'salary' => '',
                'position' => '',
                'level' => '',
                'experience' => '',
                'description' => '',
                'require' => '',
                'benefit' => '',
                'record' => '',
                'lat' => '',
                'lng' => '',
                'video' => '',
            );
        }

        $_POST['user_id'] = $_SESSION['userLoggedIn']['id'];
        if (isset($_POST['info'])) {
            unset($_POST['info']);
            $this->_addInfor($data);
        } elseif (isset($_POST['recruit'])) {
            unset($_POST['recruit']);
            $this->_addRecruit($data);
        } elseif (isset($_POST['map'])) {
            unset($_POST['map']);
            $this->_addMap($data);
        } else {
            $this->_data['content'] = $this->load->view('company/add', $data, true);
            $this->load->view('layout/frontend/index', $this->_data);
        }
    }

    private function _addMap() {
        if ($_POST['company_id']) {
            $company_id = $_POST['company_id'];
            unset($_POST['company_id']);
        }

        $this->form_validation->set_rules('lat', 'Vị trí không hợp lệ', 'trim|required|decimal');
        $this->form_validation->set_rules('lng', 'Vị trí không hợp lệ', 'trim|required|decimal');

        if ($this->form_validation->run() == FALSE) { // not validate form
            $this->_data['content'] = $this->load->view('company/add', $data, true);
            $this->load->view('layout/frontend/index', $this->_data);
        } else {
            if (isset($company_id)) {
                $this->companymodel->update($company_id, $_POST);
                $this->session->set_flashdata('message', 'Đã thay đổi thành công!');
            } else {
                $this->companymodel->add($_POST);
                $this->session->set_flashdata('message', 'Đã thêm mới thành công!');
            }
            redirect('company/add');
        }
    }

    private function _addInfor($data) {
        if ($_POST['company_id']) {
            $company_id = $_POST['company_id'];
            unset($_POST['company_id']);
        }
        $isUniqueName = ''; //(isset($company_id) && $_POST['name'] == $data['company']['name']) ? '' : '|is_unique[companys.name]';

        $this->form_validation->set_rules('name', 'Tên công ty', 'trim|required|xss_clean' . $isUniqueName);
        $this->form_validation->set_rules('abbreviation', 'Tên viết tắt', 'trim|xss_clean');
        $this->form_validation->set_rules('english_name', 'Tên tiếng Anh', 'trim|xss_clean');
        $this->form_validation->set_rules('address', 'Địa chỉ', 'trim|xss_clean');
        $this->form_validation->set_rules('tax_code', 'Mã số thuế', 'trim|xss_clean');
        $this->form_validation->set_rules('tel', 'Điện thoại / Fax', 'trim|xss_clean');
        $this->form_validation->set_rules('website', 'Website', 'trim|xss_clean');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('representative', 'Người đại diện', 'trim|xss_clean');
        $this->form_validation->set_rules('cellphone', 'Di động', 'trim|xss_clean');
        $this->form_validation->set_rules('charter_capital', 'Vốn điều lệ', 'trim|xss_clean');
        $this->form_validation->set_rules('business_types', 'Loại hình doanh nghiệp', 'trim|required|xss_clean');
        $this->form_validation->set_rules('businesses', 'Lĩnh vực kinh doanh', 'trim|required|xss_clean');
        $this->form_validation->set_rules('business_license_issued_on', 'Giấy phép cấp ngày', 'trim|xss_clean');
        $this->form_validation->set_rules('other_businesses', 'Ngành nghề kinh doanh khác', 'trim|xss_clean');
        $this->form_validation->set_rules('posting_area', 'Khu vực đăng tin', 'trim|required|xss_clean');
        $this->form_validation->set_rules('company_background', 'Giới thiệu doanh nghiệp', 'trim|required|xss_clean');

        if ($this->form_validation->run() == FALSE) { // not validate form 
            $this->_data['content'] = $this->load->view('company/add', $data, true);
            $this->load->view('layout/frontend/index', $this->_data);
        } else {
            $this->load->library('upload');
            $this->load->library('image_lib');

            if ($_POST['intro_video']) {
                $_POST['intro_video'] = str_replace('watch?v=', 'embed/', $_POST['intro_video']);
            }

            if ($_POST['name']) {
                $this->load->helper('controller');

                $_POST['slug'] = generalSlug($_POST['name']);
            }

            if (isset($company_id)) {
                $this->companymodel->update($company_id, $_POST);
                $this->session->set_flashdata('message', 'Đã thay đổi thành công!');
            } else {
                $this->companymodel->add($_POST);
                $this->session->set_flashdata('message', 'Đã thêm mới thành công!');
            }
            redirect('company/add');
        }
    }

    private function _addRecruit() {
        if ($_POST['company_id']) {
            $company_id = $_POST['company_id'];
            unset($_POST['company_id']);
        }

        $this->load->library(array('form_validation'));
        $this->form_validation->set_rules('date', 'Ngày đăng tuyển dụng', 'trim|required|xss_clean');
        $this->form_validation->set_rules('quantity', 'Số lượng cần tuyển', 'trim|required|xss_clean');
        $this->form_validation->set_rules('property', 'Tính chất', 'trim|required|xss_clean');
        $this->form_validation->set_rules('work_place', 'Địa điểm làm việc', 'trim|required|xss_clean');
        $this->form_validation->set_rules('career', 'Ngành nghề', 'trim|required|xss_clean');
        $this->form_validation->set_rules('salary', 'Mức lương', 'trim|required|xss_clean');
        $this->form_validation->set_rules('position', 'Chức vụ', 'trim|required|xss_clean');
        $this->form_validation->set_rules('level', 'Trình độ', 'trim|required|xss_clean');
        $this->form_validation->set_rules('experience', 'Kinh nghiệm', 'trim|required|xss_clean');
        $this->form_validation->set_rules('description', 'Mô tả công việc', 'trim|required|xss_clean');
        $this->form_validation->set_rules('require', 'Yêu cầu', 'trim|required|xss_clean');
        $this->form_validation->set_rules('benefit', 'Quyền lợi được hưởng', 'trim|required|xss_clean');
        $this->form_validation->set_rules('record', 'Hồ sơ dự tuyển', 'trim|required|xss_clean');

        if ($this->form_validation->run() == FALSE) { // not validate form 
            $this->_data['content'] = $this->load->view('company/add', $data, true);
            $this->load->view('layout/frontend/index', $this->_data);
        } else {
            if (isset($company_id)) {
                $this->companymodel->update($company_id, $_POST);
                $this->session->set_flashdata('message', 'Đã thay đổi thành công!');
            } else {
                $this->companymodel->add($_POST);
                $this->session->set_flashdata('message', 'Đã thêm mới thành công!');
            }
            redirect('company/add');
        }
    }

    public function addFile($type) {
        $data = ''; // file album to insert db
        $width = 626;
        $height = 379;
        if ($type == 'album') {
            $files = json_decode($_POST['dataAlbumCropJson'], TRUE);
        } else if ($type == 'intro_images') {
            $files = json_decode($_POST['dataIntroImagesCropJson'], TRUE);
            $height = 370;
        } else if ($type == 'logo') {
            $files = json_decode($_POST['datalogoCropJson'], TRUE);
            $width = 100;
            $height = 110;
        } else if ($type == 'avatar') {
            $files = json_decode($_POST['dataavatarCropJson'], TRUE);
            $width = 224;
            $height = 155;
        }
        $this->load->library('image_lib');

        //1. remove all file if edit
        if ($_POST['company_id']) {
            $path = 'upload/company/' . $type . '/' . $_SESSION['userLoggedIn']['id'];
            // Open the folder
            $dir_handle = @opendir($path) or die("Unable to open $path");
            // Loop through the files
            while ($file = readdir($dir_handle)) {
                if ($file == "." || $file == ".." || $file == "index.php")
                    continue;
                unlink('upload/company/' . $type . '/' . $_SESSION['userLoggedIn']['id'] . '/' . $file);
            }
            // Close
            closedir($dir_handle);
        }

        foreach ($files as $fileName => $fileData) {
            // 2.crop image
            $this->image_lib->initialize(array(
                'image_library' => 'gd2',
                'source_image' => 'upload/company/' . $type . '/temp/' . $fileName,
                'width' => $fileData['w'],
                'height' => $fileData['h'],
                'x_axis' => $fileData['x'],
                'y_axis' => $fileData['y'],
                'maintain_ratio' => FALSE
            ));

            if (!$this->image_lib->crop()) {
                $this->session->set_flashdata('message', $this->image_lib->display_errors());
                redirect('company/add');
                return FALSE;
            } else {
                // 3.resize image
                $this->image_lib->initialize(array(
                    'image_library' => 'gd2',
                    'source_image' => 'upload/company/' . $type . '/temp/' . $fileName,
                    'new_image' => 'upload/company/' . $type . '/' . $_SESSION['userLoggedIn']['id'] . '/' . $fileName,
                    'width' => $width,
                    'height' => $height,
                    'maintain_ratio' => TRUE
                ));
                if (!$this->image_lib->resize()) {
                    $this->session->set_flashdata('message', $this->image_lib->display_errors());
                    redirect('company/add');
                    return FALSE;
                }
            }
            $this->image_lib->clear();
            // 4.remove temp file
            unlink('upload/company/' . $type . '/temp/' . $fileName);

            $data .= $fileName . ';';
        }
        $data = trim($data, ";");

        // 5.add to db
        if ($_POST['company_id']) {
            $this->companymodel->update($_POST['company_id'], array($type => $data));
            $this->session->set_flashdata('message', 'Đã thay đổi thành công!');
        } else {
            $this->companymodel->add($data);
            $this->session->set_flashdata('message', 'Đã thêm mới thành công!');
        }

        redirect('company/add');
    }

    /**
     * Ajax upload to temp
     * 
     * @return string list file upload
     */
    public function uploadFile($type) {
        $fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
        if ($fn) {
            // AJAX call
            file_put_contents(
                    'upload/company/' . $type . '/temp/' . $fn, file_get_contents('php://input')
            );
            echo "$fn uploaded";
            exit();
        } else {
//      	// form submit - if no support ajax
//      	$files = $_FILES['fileselect'];
//      
//      	foreach ($files['error'] as $id => $err) {
//      		if ($err == UPLOAD_ERR_OK) {
//      			$fn = $files['name'][$id];
//      			move_uploaded_file(
//      				$files['tmp_name'][$id], 'upload/company/album/temp/' . $fn
//                );
//      			echo "<p>File $fn uploaded.</p>";
//      		}
//      	}
        }
    }

    public function _upload($name, $data) {
        if ($this->upload->do_upload($name)) {
            $nameImage = $this->upload->file_name;

            if ($data['resize']) {
                $this->image_lib->initialize(array(
                    'image_library' => 'gd2',
                    'source_image' => $data['source_image'] . $nameImage,
                    'width' => $data['width'],
                    'height' => $data['height'],
                    'maintain_ratio' => FALSE
                ));

                if (!$this->image_lib->resize()) {
                    $this->session->set_flashdata('message', $this->image_lib->display_errors());
                    redirect('company/add');
                    return FALSE;
                }
                $this->image_lib->clear();
            }

            return $nameImage;
        } else {
            $this->session->set_flashdata('message', $this->upload->display_errors('<div>', '</div>'));
            redirect('company/add');
            return FALSE;
        }
    }

    public function test() {
        echo '<pre>';
        var_dump($_POST);
        die;
    }

    // List tất cả comment của doanh nghiệp
    public function listComment($company_id = null, $page = 0, $isAjax = false) {
        $this->load->helper('user_helper');
        $data['comment'] = $this->company_comment_model->getCommentByCompanyId($company_id, $page * 5, 5);
        $this->_data['content'] = $this->load->view('company/listComment', $data);
    }
    
    public function type() {
        $data = '';
        $this->_data['content'] = $this->load->view('company/type', $data);
    }
        
    public function comment($user_id = null, $company_id = null, $comment = null) {
        $data['user_id'] = $user_id;
        $data['company_id'] = $company_id;
        $data['comment'] = $comment;
        $this->company_comment_model->add($data);
    }
}